package cn.haoxsf.app.system.service.impl;

import cn.haoxsf.app.common.api.enums.UserExceptionEnum;
import cn.haoxsf.app.common.exception.BaseException;
import cn.haoxsf.app.common.util.DistanceCalculationUtils;
import cn.haoxsf.app.common.util.ToolUtil;
import cn.haoxsf.app.system.entity.Member;
import cn.haoxsf.app.system.entity.MemberRepair;
import cn.haoxsf.app.system.entity.MemberRole;
import cn.haoxsf.app.system.entity.Permission;
import cn.haoxsf.app.system.mapper.MemberMapper;
import cn.haoxsf.app.system.mapper.PermissionMapper;
import cn.haoxsf.app.system.model.vo.BusinessResult;
import cn.haoxsf.app.system.model.vo.MemberResult;

import cn.haoxsf.app.system.model.vo.MemberVo;
import cn.haoxsf.app.system.service.IBusinessService;
import cn.haoxsf.app.system.service.IMemberRepairService;
import cn.haoxsf.app.system.service.IMemberRoleService;
import cn.haoxsf.app.system.service.IMemberService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author Ele  qvbanfm@qq.com
 * @since 2020-01-07
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements IMemberService {

    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private IMemberRoleService roleService;
    @Autowired
    private IMemberRepairService memberRepairService;
    @Autowired
    private IBusinessService businessService;

    /**
     * 获取用户
     *
     * @param userName 用户名
     * @return 用户
     */
    @Override
    public Member getMemberByUsername(String userName) {
        Member member = this.baseMapper.selectOne(new QueryWrapper<Member>().eq("username", userName));
        if (member == null) {
            throw new BaseException(UserExceptionEnum.NOT_USERS);
        }
        return member;
    }

    /**
     * 获取用户所有权限(包括+-权限)
     *
     * @param adminId
     */
    @Override
    public List<Permission> getPermissionList(Long adminId) {
        return permissionMapper.getPermissionList(adminId);
    }

    /**
     * 添加用户
     *
     * @param member
     * @return
     */
    @Override
    public Boolean add(Member member) {
        if (ToolUtil.isEmpty(member)) {
            return false;
        }
        Member one = this.baseMapper.selectOne(new QueryWrapper<Member>().eq("username", member.getUsername()));
        if (ToolUtil.isNotEmpty(one)) {
            if (one.getUsername().equals(member.getUsername())) {
                throw new BaseException(UserExceptionEnum.USER_ALREADY_EXISTS);
            }
            if (one.getOpenId().equals(member.getOpenId())) {
                throw new BaseException(UserExceptionEnum.OPENID_EXISTS);
            } else if (one.getPhone().equals(member.getPhone())) {
                throw new BaseException(UserExceptionEnum.TELEPHONE_PRESENCE);
            }
        }
        String encode = passwordEncoder.encode(member.getPassword());
        member.setPassword(encode);
        member.setStatus("ENABLE");
        member.setCreateTime(new Date());
        member.setIntegration(0);
        this.baseMapper.insert(member);
        return true;
    }

    @Override
    public int updateMember(Member member) {
        UpdateWrapper<Member> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("open_id",member.getOpenId());
        updateWrapper.eq("username",member.getUsername());
        member.setPassword(null);
        return  baseMapper.update(member, updateWrapper);
    }

    /**
     * 获取用户+角色
     *
     * @param userName
     * @return
     */
    @Override
    public MemberResult getMemberAndRole(String userName) {
        Member member = getMemberByUsername(userName);
        List<MemberRole> role = roleService.findRoleByMemberId(member.getId());
        MemberResult result = new MemberResult();
        BeanUtils.copyProperties(member, result);

        if (ToolUtil.isNotEmpty(role)) {
            MemberRepair memberRepair = memberRepairService.getOne(new QueryWrapper<MemberRepair>().eq("member_id", member.getId()));
            if (ToolUtil.isNotEmpty(memberRepair)) {

                result.setRealName(memberRepair.getRealName().substring(0, 1) + "师傅");
                result.setWorkState(memberRepair.getWorkState());
            } else {
                result.setRealName("暂无");
                result.setWorkState("暂无");
            }
        }
        result.setRoles(role);
        return result;
    }

    /**
     * 查询用户 如果有师傅的信息就显示
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public MemberVo getMemberAndBusinessByUsername(String userName) {
        Member memberByUsername = getMemberByUsername(userName);
        MemberVo member = new MemberVo();
        BusinessResult one = businessService.getOne(memberByUsername.getId().toString());
        BeanUtils.copyProperties(memberByUsername, member);
        member.setBusiness(one);
        return member;
    }

    /**
     * 查找附近的商户
     *
     * @param radii    半径距离(单位km)
     * @param lon      当前位置
     * @param lat      当前位置
     * @param userType 需要查询的用户类型
     * @return 附近的用户集合
     */
    @Override
    public List<Map<String, Object>> getNearbyUsers(Double radii, Double lon, Double lat, String userType) {
        final double r = 6371;//地球半径千米
        double dis = radii;//范围
        double dlng = 2 * Math.asin(Math.sin(dis / (2 * r)) / Math.cos(lat * Math.PI / 180));
        dlng = dlng * 180 / Math.PI;//角度转为弧度
        double dlat = dis / r;
        dlat = dlat * 180 / Math.PI;
        double minlat = lat - dlat;
        double maxlat = lat + dlat;
        double minlng = lon - dlng;
        double maxlng = lon + dlng;
        if (ToolUtil.isEmpty(userType)) {
            return null;
        }
        List<Map<String, Object>> business = baseMapper.getBusiness(minlng, maxlng, minlat, maxlat, userType);
        for (Map<String, Object> map : business) {
            map.put("praise", 4.99);//TODO 好评
            map.put("distance", DistanceCalculationUtils.getDistance(lat, lon, (Double) map.get("latitude"), (Double) map.get("longitude")));//TODO 距离
            map.put("orderNumber", 1);//TODO 订单数
            map.put("isShop", "YES");//TODO 是否有门店
//            map.put("workState", "OPEN".equals(map.get("workState")) ? "开工" : "收工");
//            map.put("isShop", "YES".equals(map.get("isShop")) ? "商铺认证" : "NO");
            map.remove("latitude");
            map.remove("longitude");
        }
        return business;
    }

    /**
     * 按照openid查询
     *
     * @param openId 用户openid
     * @return 结果
     */
    @Override
    public Member getMemberByOpenId(String openId) {
        return baseMapper.selectOne(new QueryWrapper<Member>().eq("open_id",openId));
    }

    /**
     * 查询全部按照openid
     *
     * @return
     */
    @Override
    public List<Member> getMemberListByOpenId() {
        return baseMapper.selectList(null);
    }
}
